var qqResData;

//登录模块功能
var Login = {
    url:{
        /** 用户管理中心：必须已登录 */
        userManage:function () {
            return "/auth/manage/postlist/1";
        }
    },
    // 页面初始化
    init:function (options) {
        var account = options.account;
        if(account){
            MrcodeUi.Alert.popLayer.popYCenterTtile("您的账户：" + account + "<br/>" + "小提示：点击本页的\"用QQ账户登录\"，可以绑定账户后快速登陆哦<br/>" +
                "注意：<br/>1. 如果登录的QQ号已经绑定了，则会直接登录到绑定的账户" +
                "<br/>2. 暂时还未提供解绑操作，如有需要请联系博客管理员99299684",
                    "注册成功","确定")
            $("#login_from input[name='password']")[0].focus();
        }
        Login.qq.loginConfig();
        login();
    },
    qq:{
        loginConfig:function () {
            QC.Login({
                btnId:"qqlogin",	//插入按钮的节点id
                size: "A_L"
            }, function(reqData, opts){//登录成功
                Login.qq.success(reqData, opts);
            }, function(opts){//注销成功
                Login.qq.logOut();
            });
        },
        success:function (reqData, opts) {
            qqResData = reqData;
            //根据返回数据，更换按钮显示状态方法
            var dom = document.getElementById(opts['btnId']),
                _logoutTemplate=[
                    //头像
                    '<span><img src="{figureurl}" class="{size_key}"/></span><br>',
                    //昵称
                    '<span> {nickname}</span><br>',
                    //退出
                    '<span><a class="submit_btn text-warning" href="javascript:QC.Login.signOut();"><span class="text-warning">注销登录·退出</span></a></span>'
                ].join("");
            dom && (dom.innerHTML = QC.String.format(_logoutTemplate, {
                nickname : QC.String.escHTML(reqData.nickname), //做xss过滤
                figureurl : reqData.figureurl_1
            }));

            var dom2 = document.getElementById("qqlogin_success"),
                _logoutTemplate=[
                    //头像
                    '<span><img src="{figureurl}" class="{size_key}"/></span><br>',
                    //昵称
                    '<span> {nickname}</span><br>',
                    //退出
                    '<span><a class="submit_btn" href="javascript:QC.Login.signOut();"><span class="text-warning">注销登录·退出</span></a></span>'
                ].join("");
            dom2 && (dom2.innerHTML = QC.String.format(_logoutTemplate, {
                nickname : QC.String.escHTML(reqData.nickname), //做xss过滤
                figureurl : reqData.figureurl_1
            }));

            $("#login_wrap").hide();
            $("#qqlogin_success_wrap").show();
            $("#mrcode-index").hide();


            // 登录成功之后，需要尝试登录，如果登录失败，就绑定
            QC.Login.getMe(function(openId, accessToken){
                tryQqlogin(openId,function (resultData) {
                    new MrcodePopLayer({
                        'position': "center",
                        'animateEntrance': 'flipInX',
                        'animateClosing': 'flipOutX',
                        'icon': "icon-spinner icon-2x icon-spin",
                        'content': resultData.msg + "<br/>自动跳转中,请稍后... ",
                    });
                    QC.Login.signOut();
                    window.location.href = "/" /*+ userAccount + "/article/list"*/;
                },function (msg) {
                    $("#account_bd_warp").show();
                });
            });
        },
        logOut:function () {
            $("#qqlogin_success_wrap").hide();
            $("#login_wrap").show();
            $("#mrcode-index").show();
        }
    }
}


$().ready(function () {
    $("#btn_wjpsd").on("click",function(){
        alertInfo("#login_info","该功能正在开发中...");
    });
    bdUserCheck();
    $("#btn-qqbd").on("click",function () {
        qqloginBd();
    });
});

function bdUserCheck() {
    $("input[name='bduser']").on("change",function () {
        var checkVal = $("input[name='bduser']:checked").val();
        if(checkVal == "1"){
            $("#bdAccount").attr("placeholder","请输入您喜爱的账户");
            $("#badPassword-warp").hide();
        }else{
            $("#bdAccount").attr("placeholder","请输入您已有的mrcode账户");
            $("#badPassword-warp").show();
        }
    });
}

// 绑定qq
function qqloginBd() {
    if(!QC.Login.check()){
        MrcodeUi.Alert.sx.danger("非法操作，还未进行qq登录,请重新登录");
        return;
    }

    var checkVal = $("input[name='bduser']:checked").val();

    var account = $("#bdAccount").val();
    var accountInfo = test("account",account);
    if(accountInfo){
        MrcodeUi.Alert.sx.danger(accountInfo);
        return;
    }

    if(checkVal == "1"){
        QC.Login.getMe(function(openId, accessToken){
            reqQqloginBd1(openId,account);
        });
    }else{
        var password = $("#badPassword").val();
        var passwordInfo = test("password",password);
        if(passwordInfo){
            MrcodeUi.Alert.sx.danger(passwordInfo);
            return;
        }
        QC.Login.getMe(function(openId, accessToken){
            reqQqloginBd2(openId,account,password);
        });
    }
}

/** 尝试使用qq登录 */
function tryQqlogin(openId,succCal,failCal) {
    var pop = null;
    $(document).ajaxStart(function() {
        pop = new MrcodePopLayer({
            'position': "center",
            'icon': "icon-spinner icon-2x icon-spin",
            'content': "请稍后.."
        });
    });
    $(document).ajaxStop(function() {
        pop.close();
    });

    $.ajax({
        url: $contextPath + "/account/con/qq/login/" + openId,
        data: {},
        type: "POST",
        dataType: 'json',
        success: function (resultData) {
            var success = resultData.success;
            var msg = resultData.msg;
            var data = resultData.data;
            if (1 == success) {
                succCal(resultData);
            } else {
                failCal(resultData);
            }
        },
        error: function (er) {
            MrcodeUi.Alert.sx.danger("服务出错,请稍后重试!");
        }
    });
    
}

function reqQqloginBd1(openid,account) {
    $.ajax({
        url: $contextPath + "/account/con/qq/bdaccount/1",
        data: {
            account:account,
            nickname:qqResData.nickname,
            figureurl_2:qqResData.figureurl_2,
            openid:openid
           
        },
        type: "POST",
        dataType: 'json',
        success: function (resultData) {
            var success = resultData.success;
            var msg = resultData.msg;
            var data = resultData.data;
            if (1 == success) {
                new MrcodePopLayer({
                    'position': "center",
                    'animateEntrance': 'flipInX',
                    'animateClosing': 'flipOutX',
                    'dialog': "confirm",
                    'title':"绑定并自动登录成功",
                    'content': "<span class='icon-exclamation-sign text-success'></span> 以下是您的账户信息,请牢记：" +
                                "<br>账户：" + data.account +
                                "<br>密码：" + data.password +
                                "<br>博客域名：" + data.blog +
                                "<br>以后您可以通过QQ快速登录，也可以用上账户密码进行登录,可登录后自行更改密码~",
                    'onConfirm': {
                        text: '我记住了',
                        style:"success",
                        action: function () {
                            window.location.href = Login.url.userManage();
                        }
                    }
                });
                QC.Login.signOut();
            } else {
                MrcodeUi.Alert.sx.danger(msg);
                /* alertErr("#info", msg);
                 btnActive("#submit_btn","正在处理中...");*/
            }
        },
        error: function (er) {
            MrcodeUi.Alert.sx.danger("服务出错,请稍后重试!");
        }
    });
}
function reqQqloginBd2(openid,account,password) {
    $.ajax({
        url: $contextPath + "/account/con/qq/bdaccount/2",
        data: {
            account:account,
            password:password,
            nickname:qqResData.nickname,
            figureurl_2:qqResData.figureurl_2,
            openid:openid

        },
        type: "POST",
        dataType: 'json',
        success: function (resultData) {
            var success = resultData.success;
            var msg = resultData.msg;
            var data = resultData.data;
            if (1 == success) {
                MrcodeUi.Alert.popLayer.popYCenter("以后您可以通过QQ快速登录，也可以通过原本的账户密码进行登录",
                    '我记住了',function () {
                        window.location.href = Login.url.userManage();
                    })
                QC.Login.signOut();
            } else {
                MrcodeUi.Alert.sx.danger(msg);
                /* alertErr("#info", msg);
                 btnActive("#submit_btn","正在处理中...");*/
            }
        },
        error: function (er) {
            MrcodeUi.Alert.sx.danger("服务出错,请稍后重试!");
        }
    });
}

function login() {
    var $loginSubmit = $("#login_submit");
    var newBtnDA = MrcodeUi.Btn.newBtnDA($loginSubmit,false);
    var btnName = $loginSubmit.attr("btnName");
    $("#login_from").validate({
        debug: true,  //调试
        rules: {
            account: {
                required: true,
                maxlength: 12,
                minlength:6
            },
            password: {
                required: true,
                maxlength: 12,
                minlength:6
            }
        },
        messages: {
            account: {
                required: "账户不能为空",
                maxlength: "长度不能大于{0}",
                minlength:"长度不能小于{0}"
            },
            password: {
                required: "密码不能为空",
                maxlength: "长度不能大于{0}",
                minlength:"长度不能小于{0}"
            }
        },
        errorElement: Comm.Ui.Jq_ValidateGroup.errorElement,
        errorClass: Comm.Ui.Jq_ValidateGroup.errorClass,
        errorPlacement: function (error, element) {
            Comm.Ui.Jq_ValidateGroup.errorPlacement(error, element);
        }, success: function (label) {
            Comm.Ui.Jq_ValidateGroup.success(label);
        },
        submitHandler: function (form) { //提交
            newBtnDA.disabled("正在登录中...");
            $.ajax({
                url: $contextPath + "/account/login/submit",
                data: $(form).serialize(),
                type: "POST",
                dataType: 'json',
                success: function (resultData) {
                    var success = resultData.success;
                    var msg = resultData.msg;
                    var data = resultData.data;
                    if (1 == success) {
                        MrcodeUi.Alert.sx.success(msg);
                        setTimeout(function(){
                            window.location.href = Login.url.userManage();
                        },"2000");
                    } else {
                        MrcodeUi.Alert.sx.danger(msg);
                        newBtnDA.active(btnName);
                    }
                },
                error: function (er) {
                    MrcodeUi.Alert.sx.danger("服务出错,请稍后重试!");
                    newBtnDA.active(btnName);
                }
            });
        }
    });
}
